import { Component, OnInit, ViewChild } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
import 'assets/js/bootstrap-switch.min.js'
import 'assets/css/bootstrap-switch.min.css'
import { DatePickerModule } from '../../shared/date-picker/date-picker.module'

declare var $: any
declare var Viewer: any
@Component({
  selector: 'sa-fund-details',
  templateUrl: './fund-details.component.html',
  styleUrls: ['./fund-details.component.css']
})
export class FundDetailsComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      arrivalAmount: {
        validators: {
          notEmpty: {
            message: '请选择到账金额'
          }
        }
      },
      serialnumber: {
        validators: {
          notEmpty: {
            message: '请输入流水单号'
          }
        }
      },
      accountingDate: {
        trigger: "change",
        validators: {
          notEmpty: {
            message: '请选择到账时间'
          }
        }
      }
    }
  }
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数

  projectId: string = '' //项目Id
  projectName: string = '' //项目名称
  projectList: any //项目数据

  formType: string = 'new'
  companyList: any = []
  paramFormat: any = {
    id: 'id',
    text: 'accountName'
  }

  CorporateAccountFrom: any = {
    id: '',
    accountId: '',
    accountName: '',
    accountType: '',
    accountingDate: '',
    arrivalAmount: '',
    serialnumber: '',
    remark: '',
    serialnumberImg: ''
  }

  tableSearchData = {
    accountName: '',
    accountId: '',
    serialnumber: '',
    startTime: '',
    endTime: ''
  }
  specifyId = {
    picker1: 'datetimepicker3',
    picker2: 'datetimepicker4'
  }

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
      this.tableSearchData.accountId = queryParams.id || ''
      this.tableSearchData.accountName = queryParams.accountName || ''
    })
  }

  //项目选中
  optionSelectedForm(data) {
    this.CorporateAccountFrom.accountId = data.id
    this.CorporateAccountFrom.accountName = data.text
    this.CorporateAccountFrom.accountType = data.option.accountType
  }
  // 时间选择回调
  dateSelect(time) {
    this.tableSearchData.startTime = time.startTime
    this.tableSearchData.endTime = time.endTime
  }
  // 初始化1天的时间
  initDate() {
    this.specifyTime = {
      startTime: this.tableSearchData.startTime,
      endTime: this.tableSearchData.endTime
    }
  }
  specifyTime: any

  @ViewChild('renewalTimeComp')
  renewalTimeComponent: any = DatePickerModule
  //时间change回调
  datePickerSelected(val) {
    this.CorporateAccountFrom.accountingDate = val.endTime
  }

  ngOnInit() {
    this.initAllProjectName().then(() => {
      this.selectProjectName()
    })
    this.load()
    this.getCompanyList()
    this.initDate()
  }

  // 项目
  getCompanyList(companyId?: string) {
    this.jsonApiService.http_obj('CorporAccount/list.html', {}).subscribe(data => {
      this.companyList = data.data
    })
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  tableSearch() {
    this.curPage = 1
    this.load()
  }
  //删除
  tableDel(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http('CorporateFinancialDetails/deleteById.html', 'id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: this.tableSearchData
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('CorporateFinancialDetails/page.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  /*
   * 新增
   */
  table_add(modal) {
    this.formType = 'new'
    this.resetForm()
    modal.show()
  }
  /*
   * 编辑
   */
  editRow(row, modal) {
    modal.show()
    this.resetForm()
    //		this.CorporateAccountFrom.id = row.id;
    this.formType = 'updata'
    for (let item in this.CorporateAccountFrom) {
      this.CorporateAccountFrom[item] = row[item]
    }

    for (let item of this.companyList) {
      if (item.id == row.accountId) {
        this.CorporateAccountFrom.accountName = item.accountName
        this.CorporateAccountFrom.accountId = item.id
        this.CorporateAccountFrom.accountType = item.accountType
        $("#select2-roleSelect2Form-container").empty();
        $("#select2-roleSelect2Form-container").attr("title",item.accountName);
        $("#select2-roleSelect2Form-container").prepend(item.accountName);
      }
    }
    
  }
  resetForm(){
    $('#CorporateAccountFrom').data('bootstrapValidator').resetForm()
    this.CorporateAccountFrom = {
      id: '',
      accountId: '',
      accountName: '',
      accountingDate: '',
      arrivalAmount: '',
      serialnumber: '',
      remark: '',
      serialnumberImg: ''
    }
    $('#roleSelect2Form').val('').trigger('change')
    // 初始化时间
    this.renewalTimeComponent.initDate()
  };
  fileList: File = null
  //上传多张
  multifileChange(files: FileList) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }

    var that = this
    let multfileList = files

    var reqdata = new FormData()
    reqdata.append('describe', '流水单图片')
    reqdata.append('businessType', '1')
    // reqdata.append('deviceId', this.page.deviceId);
    reqdata.append('type', '2') //type 1获取相对路径  2获取绝对路径

    for (var i = 0; i < multfileList.length; i++) {
      this.fileList = multfileList[i]
      const isJPG =
        this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png'
      if (!isJPG) {
        this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!')
        return
      }

      reqdata.append('files', multfileList[i])
    }

    that.jsonApiService.form_http('fileUpload/upload.html', reqdata).subscribe(data => {
      if (data.success) {
        if (data.data.length > 1) {
          this.jsonApiService.message('上传图片只能是上传一张')
        } else {
          this.CorporateAccountFrom.serialnumberImg = data.data[0]
        }
        // for (var i = 0; i < data.data.length; i++) {
        // 	that.imageInfoList.push(data.data[i]);
        // }
      }
    })

    for (let k = 0; k < $('.up').length; k++) {
      $('.up')[k].value = null
    }
  }
  //删除
  deleteImg() {
    this.CorporateAccountFrom.serialnumberImg = ''

    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
  }
  bigImg: any = ''
  bigImgClick(modal, img) {
    // modal.show();
    // this.bigImg = img;
    // this.isViewer = true;
    // if (this.isViewer && $(".viewer-container").length > 0) {
    //   System.import("assets/js/viewer/viewer.js").then(() => {
    //     System.import("assets/js/viewer/bootstrap.bundle.min.js").then(() => {
    //       System.import("assets/js/viewer/viewer.css").then(() => {
    //         this.showImg();
    //       });
    //     });
    //   });
    // } else {
    //   this.showImg();
    // }
  }

  /*
   * 关闭弹窗
   */
  modalClose(modal) {
    $('#CorporateAccountFrom').data('bootstrapValidator').resetForm()
    this.CorporateAccountFrom = {
      id: '',
      accountId: '',
      accountName: '',
      accountingDate: '',
      arrivalAmount: '',
      serialnumber: '',
      remark: '',
      serialnumberImg: ''
    }
    modal.hide()
    $('#roleSelect2Form').val('').trigger('change')
    // 初始化时间
    this.renewalTimeComponent.initDate()
  }

  // 图片关闭
  imgClose(modal) {
    modal.hide()
  }
  //图片放大
  isViewer: Boolean = false
  viewer: any
  // bigimg() {
  //   if (this.isViewer && $(".viewer-container").length > 0) {
  //     if (this.isViewer && $(".viewer-container").length > 0) {
  //       this.viewer.destroy();
  //     }

  //     System.import("assets/js/viewer/viewer.js").then(() => {
  //       System.import("assets/js/viewer/bootstrap.bundle.min.js").then(() => {
  //         System.import("assets/js/viewer/viewer.css").then(() => {
  //           this.showImg();
  //         });
  //       });
  //     });
  //   } else {
  //     this.showImg();
  //   }
  // }
  // 关闭图片查看
  closeImgModal2(modal) {
    modal.hide()
    this.imgList = []
    this.imgLocalList = []
  }
  //图片放大
  bigimg(type, row) {
    if (this.isViewer2 && $('.viewer-container').length > 0) {
      this.viewer2.destroy()
    }
    if (this.isViewer2 && $('.viewer-container').length > 0) {
      this.viewer2.destroy()
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showBigImg(type)
          })
        })
      })
    } else {
      this.showBigImg(type)
    }
  }
  showBigImg(type) {
    var that = this
    var imgList
    if (type == 'Modal2') {
      imgList = $('.imagesInfo')[0]
      this.viewer2 = new Viewer(imgList, {
        url: 'src',
        title: function (image) {
          return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
        }
      })
      that.isViewer2 = true
    }
  }

  /**
   * 图片查看的方法
   */
  imgList: any = []
  imgLocalList: any = []
  isViewer2: boolean = false //默认隐藏
  //显示图片组件
  viewer2: any = ''
  showImg(row, modal) {
    this.imgList = []
    this.imgLocalList = []
    if (row.serialnumberImg.indexOf(',') > 1) {
      this.imgList = row.serialnumberImg.split(',')
    } else {
      this.imgList.push(row.serialnumberImg)
    }
    // this.imgList.push(
    //   "https://t7.baidu.com/it/u=852388090,130270862&fm=193&f=GIF"
    // );
    let localImg
    for (var i = 0; i < this.imgList.length; i++) {
      if (this.imgList[i].indexOf('http') == -1) {
        if (this.imgList[i][0] == '/') {
          localImg = config.BaseURL + this.imgList[i].substr(1)
        } else {
          localImg = config.BaseURL + this.imgList[i]
        }
      } else {
        localImg = this.imgList[i]
      }
      this.imgLocalList.push(localImg)
    }
    modal.show()

    if (this.isViewer2 && $('.viewer-container').length > 0) {
      this.viewer2.destroy()
    }
  }

  //擦除用户所选项目名称
  delProjectName() {
    let delItem: string = '#projectNameSelect'
    let projectContainer: string = '#select2-projectNameSelect-container'
    this.tableSearchData.accountName = ''
    this.tableSearchData.accountId = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $(delItem).val('')
    $(projectContainer).empty().attr('title', '').prepend(str)
    this.load()
  }
  //初始化项目名称和账户名称选项
  selectProjectName() {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#projectNameSelect')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: this.projectList //为Select添加数据
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.tableSearchData.accountName = data.text
            that.tableSearchData.accountId = data.id
          })
        var option = new Option(that.tableSearchData.accountName, that.tableSearchData.accountId, true, true)
        $('#projectNameSelect').append(option)
      })
    })
  }
  //拉取项目名称,账户名称数据
  initAllProjectName() {
    const param = {
      searchKey: ''
    }
    let reqdata = 'data=' + JSON.stringify(param)
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('CorporAccount/list.html', reqdata).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            selectdata[i] = {
              id: userList[i].id,
              text: userList[i].accountName
            }
          }
          that.projectList = selectdata
        }
        resolve(true)
      })
    })
  }

  /*
   * form提交
   */
  apiControlSubmit(modal) {
    $('#CorporateAccountFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#CorporateAccountFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      if (!this.CorporateAccountFrom.accountId) {
        this.jsonApiService.message('请选择账户名称')
        return
      }
      if (!this.CorporateAccountFrom.serialnumberImg) {
        this.jsonApiService.message('请上传流水图片')
        return
      }
      this.jsonApiService
        .http_obj('CorporateFinancialDetails/edit.html', {
          data: JSON.stringify(this.CorporateAccountFrom)
        })
        .subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.load()
            this.modalClose(modal)
          }
        })
    }
  }
}
